<?php

namespace app\api\controller;

use alipay\aop\AopClient;
use app\common\controller\Api;
use app\common\library\Pay;
use app\common\library\Refund;
use app\common\model\MoneyLog;
use app\common\model\order\Goods as OrderGoods;
use app\common\model\order\Order;
use app\common\model\product\Member as ProductMember;
use app\common\model\User;
use app\common\model\user\Log as UserLog;
use think\Db;
use think\Log;

/**
 * 回调接口
 */
class Notify extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    /**
     * 回调
     */
    public function alipayNotify()
    {
        $post = $_POST;
        if (empty($post)) { //判断POST来的数组是否为空
            return false;
        }
        Log::write('记录日志：' . json_encode($post), 'err');
        $post['fund_bill_list'] = htmlspecialchars_decode($post['fund_bill_list']);
        $aop = new AopClient();
        $alipayrsaPublicKey = config('site.alipay_public_key');
        $check = $aop->rsaCheckV1($post, $alipayrsaPublicKey, "RSA2");
        Log::write('验证结果:' . json_encode($check));
        extract($post);
        if ($check) {
            //商户订单号
            //支付宝交易号
            if ($trade_status == 'TRADE_SUCCESS' || $trade_status == 'TRADE_FINISHED') {
                $str = substr($out_trade_no, 0, 2);
                if ($str == 'NO') {
                    Pay::orderFulfillment($out_trade_no,  $trade_no);
                }
                echo "success";
            } else {
                Log::error('trade_status不存在:');
            }
        } else {
            //验证失败
            echo "fail";   //请不要修改或删除
        }
    }

    /**
     * 微信回调
     */
    public function wechatNotify()
    {
        $data = file_get_contents('php://input');
        Log::write('验证支付：' . $data);
        $data = json_decode($data, true);
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        // php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            // $APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, 'WYa96C3GM2PLVt4opEhKwJdez59043qn');
            Log::write('支付成功：' . $orderData);
            // $orderData ='{"mchid":"1635149963","appid":"wx1c2ddbc154bece77","out_trade_no":"XX202212081422119380","transaction_id":"4200001642202212085961916819","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"order","success_time":"2022-12-08T14:22:21+08:00","payer":{"openid":"of5sB5sZ4gSQQM6wY6h6KQp1hiWA"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}';
            // Db::name('pay_log')->insert(['data' => $orderData]);
            $orderData = json_decode($orderData, true);
            if ($orderData['trade_state'] == 'SUCCESS') {
                $order_sn = $orderData['out_trade_no']; //商户订单号
                $transaction_id = $orderData['transaction_id']; //微信订单号
                $attach = $orderData['attach']; //微信订单号
                // 启动事务
                Db::startTrans();
                try {
                    /*业务处理*/
                    switch ($attach) {
                        case 'order':
                            Pay::orderFulfillment($order_sn, $transaction_id);
                            break;
                            // case 'dividend':
                            //     $log = UserLog::get(['sn' => $order_sn]);
                            //     if ($log->p_id) {
                            //         $puser = User::get($log->p_id);
                            //         $puser->setInc('total_interests', $log->p_interests);
                            //     }
                            //     $user = User::get($log->user_id);
                            //     $user->setInc('use_dividend', $log->dividend);
                            //     $user->setInc('total_interests', $log->interests);
                            //     $user->save(['group_id' => $log->group_id]);
                            //     $log->save(['state' => '1', 'paytime' => time(), 'transaction_id' => $transaction_id]);
                            //     break;
                    }
                    Db::commit();
                    //应答微信支付已处理该订单的通知
                    return;
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    Log::error($e->getMessage());
                    return $e->getMessage();
                }
            }
        }
    }

    //退款回调地址
    public static function refundNotify()
    {
        $notifiedData = file_get_contents('php://input');
        $data = json_decode($notifiedData, true);
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        //php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            //$APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, 'WYa96C3GM2PLVt4opEhKwJdez59043qn');
            $orderData = json_decode($orderData, true);
            if ($orderData['refund_status'] == 'SUCCESS') {
                $transaction_id = $orderData['transaction_id']; //退款单号
                $order = Order::get(['transaction_id' => $transaction_id]);
                if ($order->settlement == 0) {
                    return json(['code' => 'SUCCESS', 'message' => '成功']);
                }
                Refund::unify_refund($order->refund_price, $order->sn);

                // $user = User::get($order->user_id);
                //   //上级累计权益值扣除
                // if ($order->p_id) {
                //     $puser = User::get($order->p_id);
                //     if ($puser->total_interests <= $order->p_interests) {
                //         $puser->total_interests = 0;
                //         $puser->save();
                //     } else {
                //         $puser->setDec('total_interests', $order->p_interests);
                //     }
                // }
                // //分红金额扣除
                // if ($order->dividend > 0) {
                //     //扣除可分红金额
                //     if ($user->use_dividend <= $order->dividend) {
                //         $user->use_dividend = 0;
                //     } else {
                //         $user->setDec('use_dividend', $order->dividend);
                //     }
                //     //扣除合计分红金额
                //     if ($user->total_dividend <= $order->dividend) {
                //         $user->total_dividend = 0;
                //     } else {
                //         $user->setDec('total_dividend', $order->dividend);
                //     }
                // }
                // //权益值扣除
                // if ($order->interests > 0) {
                //     if ($user->total_interests <= $order->interests) {
                //         $user->total_interests = 0;
                //     } else {
                //         $user->setDec('total_interests', $order->interests);
                //     }
                // }
                // //累计消费扣除
                // if ($order->pay_money > 0) {
                //     $user->setDec('consumption', $order->pay_money);
                // }
                // //返回等级
                // if ($order->group_id > 0) {
                //     $group_id = Order::whereNotIn('id', $order->id)->where('user_id', $order->user_id)->where('group_id', '>', 0)->whereIn('status', ['1', '2', '3', '4'])->order('group_id desc')->value('group_id');
                //     if (!$group_id) {
                //         $group_id = 1;
                //         $user->grouptime = 0;
                //     }
                //     $user->group_id = $group_id;
                // }
                // //上级累计权益值扣除
                // // if ($order->interests > 0) {
                // //     if ($order->interests >= $user->total_interests) {
                // //         $order->refund_interests = $user->total_interests;
                // //     }
                // //     if ($order->interests < $user->total_interests) {
                // //         $order->refund_interests = $order->interests;
                // //     }
                // //     $user->use_dividend = $order->refund_interests;

                // // }
                // $order->save();
                // $user->save();
                // $res = Order::where('transaction_id',  $transaction_id)->update(['status' => 6, 'returntime' => time()]);


                /*业务处理*/
                return json(['code' => 'SUCCESS', 'message' => '成功']);
            }
        }
    }
}
